#!/usr/bin/env python
import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
# import the server implementation

sensor="mcp9808"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":15,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":"MCP9808","sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

bmcp9808=False
if sensor in log_conf:
  bmcp9808=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      bmcp9808=False
  if bmcp9808:
    import Adafruit_MCP9808.MCP9808 as MCP9808
    try:
      sens_9808 = MCP9808.MCP9808()
    except:
      bmcp9808 = False
    else:
      sens_9808.begin()
      mcp_sigma=parameter['sigma']
      if "sigma" in log_conf[sensor]:
        parameter['sigma']=int(log_conf[sensor]['sigma'])
        if parameter['sigma'] < 1:
          parameter['sigma']=1
      parameter["i2c"]=0
      parameter["var_name"]="temperature"
      mcp_data=meas_data(parameter)
      if "sqlserver" in log_conf:
        hostname="localhost"
        port=8080
        mcp_data.set_sql(host=hostname,port=port)
      if "opensensemap" in log_conf[sensor]:
        osm=log_conf[sensor]['opensensemap']
        if "sensebox_id" in osm:
          sid=osm['sensebox_id']
          if "sensors" in osm:
            if "temperature" in osm['sensors']:
              mcp_data.set_sensebox(sid,osm['sensors']['temperature'])
      bmqtt=False
      if "mqtt" in log_conf:
        bmqtt=True
        lcmq=log_conf['mqtt']
        mbroker=""
        if 'broker' in lcmq:
          mbroker=lcmq['broker']
        else:
          bmqtt=False
        mport=1883
        if 'port' in lcmq:
          mport=lcmq['port']
        if bmqtt:
          mcp_data.set_mqtt(broker=mbroker,port=mport)


if bmcp9808:
  while True:
  
  # read bme280 (temperature, humidity, pressure)
    mcp_data.append(sens_9808.readTempC())
    time.sleep(parameter['wait'])


# close the client
print("done")


